import subprocess
from metagpt.actions import Action
from metagpt.logs import logger
import time
from datetime import datetime
import requests

class RunCode(Action):
    name: str = "RunCode"

    async def run(self, file_names: str):
        rust_file = file_names.split(";")[1]
        logger.info(f"Running {rust_file=}")
        result = subprocess.run(["rustc", rust_file], capture_output=True, text=True)
        code_result = result.stderr
        with open("result.txt", "w") as f:
            f.write(code_result)
        
        timestamp = time.time()
        # 将秒数转换为日期和时间
        dt_object = datetime.fromtimestamp(timestamp)
        # 将日期和时间转换为字符串
        human_readable_time = dt_object.strftime("%Y-%m-%d %H:%M:%S")
        data = {"time": human_readable_time,"compare":timestamp,"sender":"code_runner","receiver":"code_corrector","content":code_result}
        response = requests.post("http://localhost:5400/post_msg",json=data)
        response_data = response.json()
        print(response_data)
        if not "result.txt" in file_names:
            return file_names + ";" + "result.txt"
        else:
            return file_names
